package Explorer;

import java.util.ArrayList;
import java.util.Random;

import Perception.Percepts;
import Perception.PerceptsBase;
import Perception.Parameter;
import Agent.Util;
import Agent.AgentBase;
import Agent.Connexion;
import Agent.ActionBehaviour;
/**
 * TODO description
 */

public class RandomBehaviourExp extends ActionBehaviour {

	
	private PerceptsBase percepts;
	private Connexion con;
	private boolean verbose;
	private AgentBase ag;
	
	public RandomBehaviourExp(AgentBase ag,PerceptsBase percepts,Connexion con,boolean verbose)
	{
		super(ag,con);
		this.percepts = percepts;
		this.verbose = verbose;
	}
	
	public void action() {
		try {
			if(ag.actionToDo())
				return;
			if(!con.isConnected())
				return;
			Percepts state = percepts.getPercepts("state").get(0);
			if(verbose)
			{
				for(Parameter<String> p : state.getParams())
					System.out.println(p.getName()+"  "+p.getValue());
			}
			if(state.getParam("lastActionResult").getValue().equals("failed_resources"))
			{
				if(verbose)
					ag.println("Pas assez d'energie -> Recharge");
				performAction(Util.rechargeAction());
			}
			else if(!state.getParam("lastAction").getValue().equals("probe"))
			{
				if(verbose)
					ag.println("Analyse du noeud...");
				performAction(Util.probeAction());
			}
			else
			{
				String n = Walk();
				if(verbose)
					ag.println("Deplacement vers "+n);
				performAction(Util.gotoAction(n));
			}
			
		} catch (Exception e) {
			ag.println("Erreur : "+e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public boolean done() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private String Walk() {

		ArrayList<Percepts> list = percepts.getPercepts("visibleEdge");
		String pos = (String)(percepts.getPercepts("state").get(0).getParam("position").getValue());
		
		ArrayList<String> noeuds  = new ArrayList<String>();
		Random rand = new Random(System.currentTimeMillis());
		
		int nbNoeud = 0;
		
		for(Percepts p : list)
		{
			if(p.getParam("node1").getValue().equals(pos))
			{
				nbNoeud++;
				noeuds.add((String)(p.getParam("node2").getValue()));
			}
			else if(p.getParam("node2").getValue().equals(pos))
			{
				nbNoeud++;
				noeuds.add((String)(p.getParam("node1").getValue()));
			}
		}
		
		int i = Math.abs(rand.nextInt())% nbNoeud;
		return noeuds.get(i);
		
	}
}